package com.wht.mapper.music.impl;

import com.wht.mapper.music.FindMusicDao;
import com.wht.domain.Music;
import com.wht.domain.Singer;
import com.wht.utils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @author wanghaotian
 * time:2022/11/21,0021 21:38
 * description:
 */

public class FindMusicDaoImpl implements FindMusicDao {
//    Connection connection = JDBCUtils.getConnectionFromPool();
    private JdbcTemplate jt = new JdbcTemplate(JDBCUtils.getDs());
//    private QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<Music> selectAllMusic() {
        try {
            String sql = "select * from music ";
            List<Music> list = jt.query(sql, new BeanPropertyRowMapper<Music>(Music.class));
            return list;
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public Music selectMusicById(String id) {
        try {
            String sql = "select * from music where mid=? ";
            Music music = jt.queryForObject(sql, new BeanPropertyRowMapper<Music>(Music.class), id);
            return music;
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<Music> findByPage(Integer currentPage, Integer pageSize) {
        try {
            String sql = "select * from music,singer WHERE music.sid=singer.sid limit ?,? ";
            List<Music> musics = jt.query(sql, new BeanPropertyRowMapper<Music>(Music.class), (currentPage-1)*pageSize, pageSize);
            List<Singer> singers = jt.query(sql, new BeanPropertyRowMapper<Singer>(Singer.class), (currentPage - 1) * pageSize, pageSize);
            for (Music music : musics) {
                for (Singer singer : singers) {
                    if(music.getSid() == singer.getSid()){
                        music.setSinger(singer);
                        break;
                    }
                }
            }
//            List<Music> list = queryRunner.query(connection,sql, new ,(currentPage-1)*pageSize, pageSize);
//            System.out.println(musics);
            return musics;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public Number findTotalCount() {
        String sql = "select count(mid) from music ";
        Number totalCount = jt.queryForObject(sql, Number.class);
        return totalCount;
    }

    @Override
    public List<Singer> selectSinger() {
        String sql = "select * from singer ";
        List<Singer> list = jt.query(sql, new BeanPropertyRowMapper<Singer>(Singer.class));
        return list;
    }
}
